<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab" type="border-card">
			<el-tab-pane label="基本信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>基本信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_Name_FormItem"
										prop="Entity.Name"
										:rules="[{ required: true, message: '需求池名称为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="需求池名称" tooltip="需求池的名称" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" disabled class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_Code_FormItem"
										prop="Entity.Code"
										:rules="[{ required: true, message: '需求池编号为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="需求池编号" tooltip="需求池的唯一编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Code" disabled class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_State_FormItem"
										prop="Entity.State"
										:rules="[{ required: true, message: '需求池状态为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="需求池状态" tooltip="需求池的状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.State" disabled class="width100">
											<el-option key="启用" value="启用" label="启用"></el-option>
											<el-option key="禁用" value="禁用" label="禁用"></el-option>
											<el-option key="废弃" value="废弃" label="废弃"></el-option
										></el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_IsDefault_FormItem"
										prop="Entity.IsDefault"
										:rules="[{ required: true, message: '是否默认需求池为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="是否默认需求池" tooltip="标记该需求池是否为默认需求池" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.IsDefault" disabled class="width100">
											<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
											<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PurchaserInChargeId_FormItem" prop="Entity.PurchaserInChargeId">
										<template #label>
											<WtmLabelTooltip label="采购负责人" tooltip="负责该需求池的采购专员" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.PurchaserInChargeId" disabled class="width100">
											<el-option v-for="item in stateData.AllFrameworkUsers" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
										></el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="24" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="需求池的备注说明" />
										</template>
										<el-input type="textarea" :rows="3" v-model="stateData.vmModel.Entity.Remark" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>



						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>关联信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="24" class="mb20">
									<el-form-item ref="SelectedMaterialGroupsIds_FormItem" prop="SelectedMaterialGroupsIds">
										<template #label>
											<WtmLabelTooltip label="需求池物料分类" tooltip="需求池关联的物料分类列表" />
										</template>
										<WtmTreeTransfer
											v-model="stateData.vmModel.SelectedMaterialGroupsIds"
											:data="stateData.AllSysMaterialGroups"
											left-title="列表 1"
											right-title="列表 2"
											:default-expand-all="false"
											:check-strictly="false"
											:disabled="true"
										></WtmTreeTransfer>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<el-row :gutter="20">
							<el-col :xs="24" :lg="24" class="mb20">
								<el-form-item ref="SelectedManagersIds_FormItem" prop="SelectedManagersIds" label="采购需求池管理人员关联表">
									<el-transfer
										v-model="stateData.vmModel.SelectedManagersIds"
										disabled
										:data="stateData.AllFrameworkUsers"
										:props="{ key: 'Value', label: 'Text' }"
									></el-transfer>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-card>
			</el-tab-pane>

			<el-tab-pane label="需求池明细" name="items" v-if="stateData.vmModel.Entity.ID"
				><SysPurchaseRequirementPoolEntry :search-bar="false" :toolbar="false" :is-disabled="true" :entity-id="stateData.vmModel.Entity.ID"
			/></el-tab-pane>
		</el-tabs>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysPurchaseRequirementPoolApi as api } from '/@/views/supplychain/syspurchaserequirementpool/api';
import other from '/@/utils/other';
import { ISysPurchaseRequirementPoolVm } from '/@/views/supplychain/syspurchaserequirementpool/api/interface';
import { ISysSelectType, IViewModel } from '/@/types/common';
import SysPurchaseRequirementPoolEntry from '/@/views/supplychain/syspurchaserequirementpoolentry/index.vue';
import { commonApi } from '/@/api/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');

const stateData = reactive<IViewModel<ISysPurchaseRequirementPoolVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Name: null,
			Code: null,
			TotalAmount: null,
			UrgentCount: 0,
			State: null,
			IsDefault: false,
			PurchaserInChargeId: null,
			Remark: null,
			MaterialGroups: null,
			Managers: null,
		},
		SelectedMaterialGroupsIds: [],
		SelectedManagersIds: [],
		ActionName: null,
		IsMyApprove: null,
	},
	AllFrameworkUsers: [] as ISysSelectType[],
	AllSysMaterialGroups: [] as ISysSelectType[],
});

// 取消
const onClose = () => {
	closeDialog();
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysPurchaseRequirementPool/GetFrameworkUsers', [], false).then((x) => (stateData.AllFrameworkUsers = x)),
		// 使用树形接口获取物料分组数据，直接使用树形结构
		commonApi()
			.getMaterialGroupTree()
			.then((treeData: any[]) => {
				// 直接使用树形数据，不需要扁平化
				stateData.AllSysMaterialGroups = treeData || [];
			})
			.catch((error: any) => {
				console.error('加载物料分组树形数据失败:', error);
				// 如果树形接口失败，回退到原来的扁平接口
				return other
					.getSelectList('/api/SysPurchaseRequirementPool/GetSysMaterialGroups', [], false)
					.then((x) => (stateData.AllSysMaterialGroups = x));
			}),
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => other.setValue(stateData.vmModel, x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
